﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WMSSoft.Lib.Enums;
using WMSSoft.Lib.Interfaces;
using WMSSoft.Lib.WinKStart;
using WMSSoft.Lib.WinKStart.Model.MenuConfig;

namespace WMSSoft.WinKStart.Functions
{    
    public class CSearch : iWinKStartFunctions
    {
        cWinKStartFunction m_FunctionConfig = null;

        #region Interface Members
        /// <summary>
        /// Interface Member to Initialise the Function
        /// </summary>
        public void Init()
        {
            //Nothing TODO
        }

        /// <summary>
        /// Run the Code for this WinKStart Function
        /// </summary>
        /// <param name="DataSource">DataSource to work with Data from</param>
        /// <param name="Filter">Path to specify the Sub - Folder in DataSource</param>
        /// <param name="Data">Data from GUI to work with</param>
        /// <returns></returns>
        public bool Run(Dictionary<string, object> Data)
        {
            try
            {
                if (Data.ContainsKey("Function_Config") == true)
                {
                    //m_Config = (cMenuConfigReader)Data["WinKStart_Config"];
                    m_FunctionConfig = (cWinKStartFunction)Data["Function_Config"];

                    if (Data.ContainsKey("Text") == true)
                    {
                        RunLocalSearch((string)Data["Text"]);

                        //Web Search
                        RunSearchSearchEngines((string)Data["Text"]);
                    }

                    return true;
                }
                else
                    return false;
            }
            catch (Exception Ex)
            {
                throw new Exception("Error running Function 'Search'!", Ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public void Destroy()
        {
            //Nothing TODO
        }

        #endregion

        #region Private Functions
        void RunLocalSearch(string Pattern)
        {
            try
            {
                if ( m_FunctionConfig != null)
                {
                    if (cUserSettingsReader.ConfigLoaded == true)
                    {                                             
                        Dictionary<string,string>.KeyCollection tmpKeys = cUserSettingsReader.SearchableDataSources.Keys;
                        //Iterate each search-able DataSource
                        foreach (string KeyItem in tmpKeys)
                        {
                            RunLocalSearchDataSource(KeyItem, Pattern);                            
                        }
                    }
                }
                else throw new Exception("Can't read configuration!");
            }
            catch (Exception Ex)
            {
                throw new Exception("Unable to search '" + Pattern + "'!", Ex);
            }
        }

        void RunLocalSearchDataSource(string DataSource, string Pattern)
        {
            cStartmenuItem oCurrentSearchData = null;
            StartmenuSearch oSearch = new StartmenuSearch();

            //Get Search-able DataSource - Data
            oCurrentSearchData = cMenuConfigReader.DataSources.GetData(DataSource, "");
            oSearch.SearchItem(oCurrentSearchData, Pattern);

            cStartmenuItem oSearchResultDataSource = null;
            iWinKStartDataSource oDSInstance = cMenuConfigReader.DataSources.DatasourceItems[m_FunctionConfig.DataSource].InstanceDataSourceItem;
            if (oDSInstance != null)
            {
                oSearchResultDataSource = cMenuConfigReader.DataSources.GetData(m_FunctionConfig.DataSource, m_FunctionConfig.Filter);
                if (oDSInstance.Data != null)
                {
                    System.Drawing.Icon tmpIcon = null;
                    if (oDSInstance.Data.ChildItems.ContainsKey(DataSource) == false)
                        oDSInstance.AddItem(new cStartmenuItem(DataSource, DataSource, eLinkExecutionTypes.Program,
                                                                            "", eExecutionProcedure.Unknown, eItemType.Folder, "", tmpIcon,
                                                                            oSearchResultDataSource, "", "", oSearchResultDataSource.UserStartMenuPath,
                                                                            oSearchResultDataSource.AllUsersStartMenuPath),"");



                    //Remove existing Search Items
                    oDSInstance.ClearItems(DataSource.ToUpper());
                    //Apply New Search Items
                    oDSInstance.AddChilds(oSearch.SearchResult.ChildItems, DataSource.ToUpper());

                }
            }
        }

        void RunSearchSearchEngines(string Pattern)
        {
            try
            {
                Dictionary<string,SearchEngineItem>.KeyCollection KeyItems = cMenuConfigReader.SearchEngines.SearchEngines.Keys;
                cMenuConfigReader.SearchEngines.UpdatedSearchEngine += SearchEngines_UpdatedSearchEngine;

                foreach (string KeyItem in KeyItems)
                {
                    if (cUserSettingsReader.IsInstalledSearchEngine(KeyItem) == true)
                    {
                        cMenuConfigReader.SearchEngines.Search(KeyItem, Pattern, 100);
                    }
                }
            }
            catch (Exception Ex)
            {
                throw new Exception("Can't search using SearchEngines!", Ex);
            }
        }

        void SearchEngines_UpdatedSearchEngine(object sender, iWinKStartSearchEngine e)
        {
            if (sender != null )
            {
                cStartmenuItem oSearchResultParent = null;
                iWinKStartSearchEngine oSender = (iWinKStartSearchEngine)sender;
                iWinKStartDataSource oDSInstance = cMenuConfigReader.DataSources.DatasourceItems[m_FunctionConfig.DataSource].InstanceDataSourceItem;
                 if (oDSInstance != null)
                 {
                     oSearchResultParent = cMenuConfigReader.DataSources.GetData(oSender.DataSourceName, "");
                     System.Drawing.Icon tmpIcon = null;
                     if (oDSInstance.Data.ChildItems.ContainsKey(oSender.Name) == false)
                         oDSInstance.AddItem(new cStartmenuItem(oSender.Name, oSender.Name, eLinkExecutionTypes.Program,
                                                                             "", eExecutionProcedure.Unknown, eItemType.Folder, "", tmpIcon,
                                                                             oSearchResultParent, "", "", oSearchResultParent.UserStartMenuPath,
                                                                             oSearchResultParent.AllUsersStartMenuPath), "");
                     //((iWinKStartSearchEngine)sender).SearchResult
                     //Remove existing Search Items
                     oDSInstance.ClearItems(oSender.Name.ToUpper());
                     //Apply New Search Items
                     oDSInstance.AddChilds(oSender.SearchResult.ChildItems, oSender.Name.ToUpper());
                 }
            }
        }

        #endregion
    }

}
